package mc.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mc.bus.IBazaPacjentow;
import mc.domain.Pacjent;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
/**
 * 
 * @author nickname
 * 
 *Umozliwia wyszukiwanie pacjentow w zaleznosci od podanych kryteriow
 *formView - formularz i ustalona ilosc ostanio dodanych pacjentow
 *successView - formularz z poprzednio wprowadzonymi danymi i wyniki wyszukiwania
 *
 */
public class ShowPacjenciList extends SimpleFormController {


	private IBazaPacjentow bazapacjentow;
	private ResourceBundleMessageSource messagesource;
	
	protected boolean isFormSubmission(HttpServletRequest request) {
	
		return !request.getParameterMap().isEmpty();
	
}
	
	
	@Override
	protected Map referenceData(HttpServletRequest arg0) throws Exception {
		
		String now = (new java.util.Date().toString());
		Map<Object,Object> referencjeData = new HashMap<Object, Object>();
		referencjeData.put("pacjenci", bazapacjentow.getLatestPacjent(10));
		referencjeData.put("czas", now);
		return referencjeData;
	}

	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {

	   SimpleDateFormat dateFormat = new SimpleDateFormat(messagesource.getMessage("data.format", null, null));
       dateFormat.setLenient(false);
       binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
       binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));

    
	}
		
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		
	   	Pacjent p = (Pacjent) command;
		String now = (new java.util.Date().toString());
		Map<Object, Object> model = (HashMap<Object,Object>) errors.getModel();  //dane z formularza przed bindowaniem
		
			
		model.put("pacjenci", bazapacjentow.getPacjentByExample(p));
		model.put("czas", now);
			
		
		return new ModelAndView(getSuccessView(),model);
	}

	public IBazaPacjentow getBazapacjentow() {
		return bazapacjentow;
	}

	public void setBazapacjentow(IBazaPacjentow bazapacjentow) {
		this.bazapacjentow = bazapacjentow;
	}
	
	public ResourceBundleMessageSource getMessagesource() {
		return messagesource;
	}

	public void setMessagesource(ResourceBundleMessageSource messagesource) {
		this.messagesource = messagesource;
	}

}
